
const router = require('koa-router')();
const url = require('url');
const ueditor = require('koa2-ueditor');

const index = require('./admin/index.js');
const login = require('./admin/login.js');
const user = require('./admin/user.js');
const manage = require('./admin/manage.js');
const articlecate = require('./admin/articlecate.js');
const article = require('./admin/article.js');
const focus = require('./admin/focus.js');
const link = require('./admin/link.js');
const nav = require('./admin/nav.js');
const setting = require('./admin/setting.js');


// 配置中间件(获取url地址、 登录权限)
router.use(async (ctx, next) => {
	
	// 左侧菜单选中判断值
	let codePath = url.parse(ctx.request.url).pathname;
	let pathArr = codePath.substring(1).split('/');
	
	// 模板引擎配置全局变量
	ctx.state.__HOST__ = 'http://' + ctx.request.header.host;
	
	//配置全局信息
	ctx.state.G = {
		userinfo: ctx.session.userinfo,
		urlArr: pathArr,
		referer: ctx.request.headers['referer']
	}
	
	// 登录权限判断
	if(!ctx.session.userinfo && (codePath !== '/admin/login' && codePath !== '/admin/login/code')){
		ctx.redirect('/admin/login');
		return;
	}
	
	await next();
});


router.use(index);
router.use('/login', login);
router.use('/user', user);
router.use('/manage', manage);
router.use('/articlecate', articlecate);
router.use('/article', article);
router.use('/focus', focus);
router.use('/link', link);
router.use('/nav', nav);
router.use('/setting', setting);


// 配置koa2-ueditor图片上传的地址
router.all('/editor/controller', ueditor(['static', {
    imageAllowFiles: ['.png', '.jpg', '.jpeg'],
    imagePathFormat: '/upload/ueditor/image/{yyyy}{mm}{dd}/{filename}'
}]))

module.exports = router.routes();